package org.ansj.solr;

import java.io.IOException;
import java.io.Reader;
import java.util.Map;

import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.util.ResourceLoader;
import org.apache.lucene.analysis.util.ResourceLoaderAware;
import org.apache.lucene.analysis.util.TokenizerFactory;
import org.apache.lucene.util.AttributeSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Bill
 */
public class ANSJTokenizerFactory extends TokenizerFactory implements ResourceLoaderAware {

    static final Logger logger = LoggerFactory.getLogger(ANSJTokenizerFactory.class);
    private ThreadLocal<ANSJTokenizer> tokenizerLocal = new ThreadLocal<>();    
    
    public ANSJTokenizerFactory(Map<String, String> args){
        super(args);
    }
    
    @Override
    public void inform(ResourceLoader loader) throws IOException {
    }

    @Override
    public Tokenizer create(AttributeSource.AttributeFactory af, Reader input) {
        ANSJTokenizer tokenizer = tokenizerLocal.get();
        if (tokenizer == null) {
            tokenizer = newTokenizer(input);
        } else {
            try {
                tokenizer.setReader(input);
                tokenizer.reset();
            } catch (IOException e) {
                tokenizer = newTokenizer(input);
            }
        }

        return tokenizer;
    }

    private ANSJTokenizer newTokenizer(Reader input) {
        ANSJTokenizer tokenizer = new ANSJTokenizer(input);
        tokenizerLocal.set(tokenizer);
        return tokenizer;
    }
    
}